#!/usr/bin/env python3
"""
Git代码仓库提交统计分析 Streamlit 应用程序
支持GitCode和GitLab平台的仓库获取和提交分析功能
"""

import os
from datetime import datetime
from typing import List, Dict, Tuple

# 尝试加载环境变量（如果dotenv可用）
try:
    from dotenv import load_dotenv

    load_dotenv()
except ImportError:
    # 如果dotenv不可用，跳过加载
    pass

import pandas as pd
import streamlit as st

# 导入UI模块
from ui.gitcode_interface import GitCodeInterface as GitCodeUI
from ui.gitlab_interface import GitLabInterface as GitLabUI
from ui.common_utils import CommonUtils

# 页面配置
st.set_page_config(
    page_title="Git仓库提交统计分析",
    page_icon="📊",
    layout="wide",
    initial_sidebar_state="expanded"
)

# 渲染自定义CSS样式
CommonUtils.render_custom_css()


def init_session_state():
    """初始化会话状态"""
    if 'repos_data' not in st.session_state:
        st.session_state.repos_data = None
    if 'commits_data' not in st.session_state:
        st.session_state.commits_data = None
    if 'selected_repo' not in st.session_state:
        st.session_state.selected_repo = None


def get_activity_thresholds(time_range: str):
    """根据时间周期计算活跃天数阈值"""
    return CommonUtils.get_activity_thresholds(time_range)


def sidebar_config() -> Tuple[str, str, str, str, str, datetime]:
    """配置侧边栏"""
    return CommonUtils.render_sidebar_config()


def render_gitlab_analysis_app(access_token, org_name, since_date, time_range, platform, gitlab_url):
    """渲染GitLab分析应用"""
    st.markdown('<h1 class="main-header">🔬 GitLab核心指标分析</h1>', unsafe_allow_html=True)

    # 初始化GitLab界面
    gitlab_interface = GitLabUI()

    # 构建配置字典
    from datetime import datetime, timedelta

    # GitLab分析使用物化视图，不需要动态时间范围
    start_date = datetime.now() - timedelta(days=180)  # 默认值，实际不使用

    # 添加GitLab特有的侧边栏配置
    st.sidebar.markdown("### 📊 GitLab分析配置")

    # 活跃度配置
    min_active_days = st.sidebar.slider(
        "最小活跃天数",
        min_value=1,
        max_value=365,
        value=20,
        help="筛选活跃天数大于此值的贡献者",
        key="gitlab_analysis_min_active_days"
    )

    # 数据范围配置
    data_range = st.sidebar.radio(
        "数据范围",
        options=["全部数据", "半年数据"],
        index=0,
        help="选择分析使用的数据范围",
        key="gitlab_analysis_data_range"
    )

    use_6month_view = (data_range == "半年数据")

    # 显示配置
    show_detailed_metrics = st.sidebar.checkbox(
        "显示详细指标",
        value=True,
        help="是否显示所有详细的评估指标",
        key="gitlab_analysis_show_detailed_metrics"
    )

    show_trend_analysis = st.sidebar.checkbox(
        "显示趋势分析",
        value=False,
        help="是否显示全年与半年数据的趋势对比",
        key="gitlab_analysis_show_trend_analysis"
    )

    max_contributors = st.sidebar.slider(
        "最大显示人数",
        min_value=5,
        max_value=100,
        value=int(os.getenv('GITLAB_DEFAULT_MAX_CONTRIBUTORS', '50')),
        help="排行榜最多显示的贡献者数量",
        key="gitlab_analysis_max_contributors"
    )

    # 构建配置字典
    config = {
        'gitlab_url': gitlab_url,
        'start_date': start_date,
        'end_date': datetime.now(),  # 结束日期为当前日期
        'min_active_days': min_active_days,
        'use_6month_view': use_6month_view,
        'show_detailed_metrics': show_detailed_metrics,
        'show_trend_analysis': show_trend_analysis,
        'max_contributors': max_contributors
    }

    # 主要内容区域
    tab1, tab2, tab3 = st.tabs(["📊 团队概览", "🚀 贡献者排行榜", "📈 详细分析"])

    with tab1:
        gitlab_interface.display_summary_dashboard(config)

    with tab2:
        gitlab_interface.display_top_contributors(config)

    with tab3:
        gitlab_interface.display_detailed_analysis(config)

    # 页脚
    st.markdown("---")
    gitlab_interface.display_platform_info()


def fetch_repositories(platform: str, access_token: str, org_name: str = None,
                       group_id: str = None) -> pd.DataFrame:
    """获取仓库列表"""
    if platform == "GitCode":
        interface = GitCodeUI()
        return interface.fetch_repositories(access_token, org_name)
    else:  # GitLab
        interface = GitLabUI()
        return interface.fetch_repositories(access_token, group_id)


def fetch_commits(platform: str, access_token: str, project_id: str, since_date: str = None) -> pd.DataFrame:
    """获取提交记录"""
    if platform == "GitCode":
        interface = GitCodeUI()
        return interface.fetch_commits(access_token, project_id, since_date)
    else:  # GitLab
        interface = GitLabUI()
        return interface.fetch_commits(access_token, project_id)


def fetch_overall_analysis(platform: str, access_token: str, repos_df: pd.DataFrame, since_date: str) -> List[
    pd.DataFrame]:
    """获取整体分析数据"""
    if platform == "GitCode":
        interface = GitCodeUI()
        return interface.fetch_overall_analysis(access_token, repos_df, since_date)
    else:  # GitLab
        interface = GitLabUI()
        return interface.fetch_overall_analysis(access_token, repos_df)


def fetch_student_analysis(platform: str, access_token: str, repos_df: pd.DataFrame, since_date: str = None,
                           org_name: str = None) -> List[Dict]:
    """获取提交者级别的详细分析数据"""
    if platform == "GitCode":
        interface = GitCodeUI()
        return interface.fetch_student_analysis(access_token, org_name, repos_df, since_date)
    else:  # GitLab
        interface = GitLabUI()
        return interface.fetch_student_analysis(access_token, repos_df)


def display_repo_overview(df: pd.DataFrame, platform: str = "GitCode"):
    """显示仓库概览"""
    CommonUtils.display_repo_overview(df, platform)


def display_commits_analysis(df: pd.DataFrame, repo_name: str, platform: str = "GitCode"):
    """显示提交分析"""
    CommonUtils.display_commits_analysis(df, repo_name, platform)


def load_username_name_mapping():
    """加载用户名姓名映射"""
    return CommonUtils.load_username_name_mapping()


def load_user_info_mapping():
    """加载完整的用户信息映射（包括姓名、部门、状态）"""
    return CommonUtils.load_user_info_mapping()


def get_display_name(username, name_mapping):
    """获取显示名称，优先使用映射的姓名，如果姓名为空则使用用户名"""
    return CommonUtils.get_display_name(username, name_mapping)


def display_student_analysis(student_stats: List[Dict], time_range: str = "最近1年"):
    """显示提交者级别的详细分析"""
    CommonUtils.display_student_analysis(student_stats, time_range)


def display_overall_analysis(overall_data: List[pd.DataFrame], time_range: str):
    """显示整体分析结果"""
    CommonUtils.display_overall_analysis(overall_data, time_range)


def main():
    """主函数"""
    # 初始化会话状态
    init_session_state()

    # 侧边栏配置
    access_token, org_name, since_date, time_range, platform, gitlab_url = sidebar_config()

    # 根据平台选择渲染不同的界面
    if platform == "GitLab":
        render_gitlab_analysis_app(access_token, org_name, since_date, time_range, platform, gitlab_url)
        return

    # GitCode平台分析
    # 页面标题
    st.markdown('<h1 class="main-header">📊 Git仓库提交统计分析</h1>', unsafe_allow_html=True)

    # 主要内容区域
    tab1, tab2, tab3 = st.tabs(["🏢 仓库概览", "📈 提交分析", "🌍 整体分析"])

    with tab1:
        st.header("仓库概览")

        if st.button("🔄 获取仓库列表", type="primary"):
            # 验证逻辑：GitCode需要access_token和org_name，GitLab只需要access_token
            if not access_token:
                st.error("请填写Access Token")
            elif platform == "GitCode" and not org_name:
                st.error("请填写组织名称")
            else:
                repos_df = fetch_repositories(platform, access_token, org_name)
                if not repos_df.empty:
                    st.session_state.repos_data = repos_df
                    st.success(f"成功获取 {len(repos_df)} 个仓库")

        # 显示仓库数据
        if st.session_state.repos_data is not None:
            display_repo_overview(st.session_state.repos_data, platform)

    with tab2:
        st.header("提交分析")

        # 仓库选择
        if st.session_state.repos_data is not None and not st.session_state.repos_data.empty:
            repo_options = st.session_state.repos_data['name'].tolist()
            selected_repo = st.selectbox(
                "选择要分析的仓库",
                repo_options,
                help="从已获取的仓库列表中选择一个进行提交分析",
                key="main_selected_repo"
            )

            if st.button("📊 分析提交记录", type="primary"):
                if not access_token or not selected_repo:
                    st.error("请选择仓库并确保Access Token有效")
                else:
                    # 获取project_id
                    selected_repo_data = st.session_state.repos_data[
                        st.session_state.repos_data['name'] == selected_repo]
                    if not selected_repo_data.empty:
                        project_id = selected_repo_data.iloc[0]['id']
                        commits_df = fetch_commits(platform, access_token, project_id,
                                                   since_date) if platform == "GitCode" else fetch_commits(platform,
                                                                                                           access_token,
                                                                                                           project_id)
                    else:
                        st.error("无法找到选中仓库的ID")
                        commits_df = pd.DataFrame()
                    if not commits_df.empty:
                        st.session_state.commits_data = commits_df
                        st.session_state.selected_repo = selected_repo
                        st.success(f"成功获取 {len(commits_df)} 条提交记录")
        else:
            st.info("请先在'仓库概览'标签页中获取仓库列表")

        # 显示提交分析
        if st.session_state.commits_data is not None and st.session_state.selected_repo:
            display_commits_analysis(st.session_state.commits_data, st.session_state.selected_repo, platform)

    with tab3:
        st.header("整体分析")

        if st.session_state.repos_data is not None and not st.session_state.repos_data.empty:
            st.info("📊 分析所有仓库的贡献者活动情况")

            if st.button("🚀 开始提交者详细分析", key="student_analysis_btn"):
                # 验证逻辑：GitCode需要access_token和org_name，GitLab只需要access_token
                if not access_token:
                    st.error("请填写Access Token")
                elif platform == "GitCode" and not org_name:
                    st.error("请填写组织名称")
                else:
                    student_stats = fetch_student_analysis(
                        platform,
                        access_token,
                        st.session_state.repos_data,
                        since_date,
                        org_name=org_name
                    ) if platform == "GitCode" else fetch_student_analysis(
                        platform,
                        access_token,
                        st.session_state.repos_data,
                        org_name=org_name
                    )
                    if student_stats:
                        display_student_analysis(student_stats, time_range)
                    else:
                        st.error("获取提交者统计数据失败")

            # 显示整体分析结果
            if 'overall_data' in st.session_state and st.session_state.overall_data:
                display_overall_analysis(st.session_state.overall_data, time_range)
        else:
            st.info("请先在'仓库概览'标签页中获取仓库列表")

    # 页脚
    st.markdown("---")
    st.markdown(
        "<div style='text-align: center; color: #666;'>"
        "GitCode 提交统计分析工具 | 基于 Streamlit 构建"
        "</div>",
        unsafe_allow_html=True
    )


if __name__ == "__main__":
    main()
